<?php

define('DOC_ROOT', $_SERVER['DOCUMENT_ROOT']);

require_once DOC_ROOT . '/src/php/Utils.php';
require_once DOC_ROOT . '/src/php/Config.php';

$data = PUtil::getFileList2Array(PUtil::getFilePath('/api_doc', false), 'resource|index.html|nav.html');

$rs = array(
    'list' => array()
);

foreach ($data as $val) {
    deal($rs, $val);
}

smartyNewFile(DOC_ROOT . '/api_doc/', 'nav.tpl', $rs);

echo json_encode(array(
    'ret' => 0,
    'msg' => 'Success!'
));
/* ================================= */
/* ============ 处理数据 =========== */
/* ================================= */

function deal(&$ary, $val) {
    $tmp = explode('/', $val);
    $l = count($tmp);
    dealRecall($tmp, $ary, 0, $l, $val);
}

function dealRecall($src, &$list, $idx, $len, $val) {
    if ($idx < $len) {
        if (!array_key_exists($src[$idx], $list['list'])) {
            $list['list'][$src[$idx]] = array(
                'name' => $src[$idx],
                'list' => array(),
            );
            if ($idx == $len - 1) {
                $list['list'][$src[$idx]]['url'] = $val;
            }
        }
        dealRecall($src, $list['list'][$src[$idx]], $idx + 1, $len, $val);
    } else {
        return;
    }
}

/* ================================= */
/* ==smarty方式 创建HTML文件模板=== */
/* ================================= */

function smartyNewFile($root, $tpl, $data) {
    require_once DOC_ROOT . '/src/php/Index.php';
    $instance = new PIndex();

    $file = fopen($root . 'nav.html', 'w');

    fwrite($file, $instance->fetchAction($tpl, $data));
    fclose($file);
}